import requests,re,json,time
from datetime import datetime, timedelta
from .models import Fuguo_share

def get_dates_in_range(start_date_str, end_date_str):
    # 将字符串日期转换为datetime对象
    start_date = datetime.strptime(start_date_str, '%Y-%m-%d')
    end_date = datetime.strptime(end_date_str, '%Y-%m-%d')
    
    # 初始化日期列表
    date_list = []
    
    # 当前日期从开始日期开始
    current_date = start_date
    
    # 循环，直到当前日期超过结束日期
    while current_date <= end_date:
        # 将当前日期格式化为字符串并添加到列表中
        date_list.append(current_date.strftime('%Y-%m-%d'))
        # 增加一天
        current_date += timedelta(days=1)
    
    return date_list
def extract_first_and_last(raw_string):
    # 使用正则表达式提取JSON部分
    json_string = re.search(r'\((.*)\)', raw_string).group(1)

    # 解析JSON字符串
    data = json.loads(json_string)
    
    return data

def get_fuguoweb_data(datetime_str):
    
    nonce = str(int(time.time() * 1000))
    url = f"https://datacenter-web.eastmoney.com/api/data/v1/get?callback=jQuery112301343923976530912_{nonce}&reportName=RPT_IF_BILLBOARD_TD&columns=ALL&filter=(SECURITY_CODE%3D%22510050%22)(TRADE_DATE%3D%27{datetime_str}%27)&pageNumber=1&pageSize=200&source=IFBILLBOARD&client=WEB&ut=b2884a393a59ad64002292a3e90d46a5&_=1729498487186"
    print(url)
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
    }
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        print(response.text)
        return response.text
    else:
        return None

def sync_data(start_date_str, end_date_str):
    datetime_strs = get_dates_in_range(start_date_str, end_date_str)
    date_dict = {}
    for datetime_str in datetime_strs:
        if Fuguo_share.objects.filter(day=datetime_str).exists():
            continue
        data = get_fuguoweb_data(datetime_str)
        data = extract_first_and_last(data)
        if data and data.get('result') and data.get('result').get('data'):
            date_dict[datetime_str] = []
            for item in data.get('result').get('data'):
                if item.get('MEMBER_NAME_ABBR') == '总成交量':
                    VOLUME = 0
                    if item.get('SELL_VOLUME'):
                        VOLUME = item.get('SELL_VOLUME')
                    elif item.get('BUY_VOLUME'):
                        VOLUME = item.get('BUY_VOLUME')
                    elif item.get('SELL_POSITION'):
                        VOLUME = item.get('SELL_POSITION')
                    elif item.get('BUY_POSITION'):
                        VOLUME = item.get('BUY_POSITION')
                    date_dict[datetime_str].append({
                        'TRADE_TYPE': item.get('TRADE_TYPE'),
                        'TARGET_NAME': item.get('TARGET_NAME'),
                        'VOLUME': VOLUME ,
                    })
                    Fuguo_share.objects.create(
                        day=datetime_str,
                        TRADE_TYPE=item.get('TRADE_TYPE'),
                        TARGET_NAME=item.get('TARGET_NAME'),
                        VOLUME=VOLUME,
                    )
    print(date_dict)